/*
 * @Author: actor
 * @Date: 2023-11-13 15:43:57
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-21 10:29:58
 * @FilePath: \i-hos-app\shared\emr\src\hooks\useHandleEmrPage.ts
 * @Description: 电子病历页面编辑操作
 */
import { onMounted, ref, Ref } from 'vue'
// 接口约束
import { IConfig } from '../interface/page'
import { IPageConfigStore } from '../interface/page'
// store数据
import { usePageConfigStore } from '../store/pageConfig'

// 获取公共的hooks
import { useCommon } from '../hooks/useCommon'
// table操作
import { useHandleTable } from '../hooks/useHandleTable'

// 公共方法
// import { generateMixed } from '../utils/index'

// 操作页面回去当前元素的所有配置
export const useHandleEmrPage = () => {
  // 解构 store的配置数据
  const configStore: IPageConfigStore = usePageConfigStore()

  // 获取设置属性
  const { setConfig, getConfig, handleHtml } = useCommon()

  // 设置对应元素
  const updatePage = (el: any, flag?: IConfig | string): void => {
    // el: 操作的节点
    // flag: 侧边栏相应的配置数据(含组件的名称)，单独字符串是组件的名称
    // 设置对应组件的样式以及右侧配置栏数据,没有组件渲染直接返回

    // 当前操作的节点
    let _speEl = handleHtml(el) as HTMLElement
    let _curEl = (_speEl != undefined || !!_speEl ? _speEl : el.target) as HTMLElement
    // 初始化当前节点的相关配置
    let _config: IConfig =
      flag == null ? (!!_curEl.dataset && _curEl.dataset.config != undefined ? JSON.parse(_curEl.dataset.config) : null) : flag

    if (!!configStore.$patch) {
      configStore.$patch((state: IPageConfigStore): void => {
        let _el_emr: boolean =
          _curEl.id == 'emr_page' ||
          _curEl.id == 'emr_page_head' ||
          _curEl.id == 'emr_page_body' ||
          _curEl.id == 'emr_page_footer'
        // _el_emr_editArea: boolean = _curEl.className.includes('emr_page_editArea')

        // 判断是不是有组件名或者配置信息以及是不是关闭按钮
        if (_config == null || !_config) {
          state.commonComponentActive = ''
          state.el = ''
          state.val = {}
          // if (!_el_emr_editArea) {
          //   state.el = !!_curEl.id ? _curEl.id : generateMixed()
          //   _curEl.id = !!_curEl.id ? _curEl.id : generateMixed()
          //   state.val = {
          //     type: _curEl.nodeName,
          //     name: '',
          //     des: '',
          //   }
          // } else {
          //   state.el = ''
          //   state.val = {}
          // }
          return
        }

        // 判断flag参数类型
        let _inString = typeof _config == 'string'
        let _tpName: string | undefined = _inString ? (_config as string) : (_config as IConfig).type

        // 设置配置侧栏的数据
        if (!_inString && !_el_emr) {
          state.el = _curEl.id
          state.val = _config as IConfig
          // if (!!_curEl.id) state.val.name = _curEl.id
        }

        // 设置自定义菜单
        if (_tpName == 'contexMenu') {
          if (_curEl.tagName == 'TABLE') {
            window.localStorage.removeItem('contexMenuType')
          } else {
            window.localStorage.contexMenuType = '1'
          }
        }

        // 动态渲染的组件名
        state.commonComponentActive = _tpName
        // if (_tpName == 'briefEdit') {
        //   state.commonComponentActive = _tpName
        // } else {
        //   state.commonComponentActive = _tpName != state.commonComponentActive ? _tpName : ''
        //   if (state.commonComponentActive == '') return
        // }

        setTimeout(() => {
          // 当前动态渲染的组件节点
          let curDom = document.querySelector(`.${_tpName}`) as HTMLElement

          // 当前操作的元素
          let _emr_page: any = (document.querySelector('.emr_page') as HTMLElement).getBoundingClientRect()
          let _client: any = _curEl.getBoundingClientRect()
          let _top: number | string = _client.top - _emr_page.top + _client.height + 15
          let _left: number | string = _client.left - _emr_page.left

          // 富文本操作组件靠左显示
          if (_tpName == 'briefEdit') {
            // let _emrBody = document.querySelector('.emr_page_body') as HTMLElement
            if (_curEl.className.includes('emr_page_editArea')) {
              _top = _client.top - _emr_page.offsetTop + 50
            } else {
              _top = (_top as number) < 50 ? (_top as number) + 30 : (_top as number) - 80
            }
            // _left = parseInt(window.getComputedStyle(_emrBody, null).getPropertyValue('margin-left'))
            // _left = _emrBody.getBoundingClientRect().left - _emr_page.offsetLeft
            _left = '50%'
          }
          // 自定义菜单
          if (_tpName == 'contexMenu') {
            // let _bodyHeight: number = document.body.clientHeight
            // let _bodyWidth: number = document.body.clientWidth
            // let _curDomHeight: number = curDom.clientHeight
            // _top = el.clientY + _curDomHeight > _bodyHeight ? _bodyHeight - _curDomHeight : el.clientY
            // _left = el.clientX + 140 > _bodyWidth ? _bodyWidth - 140 : el.clientX + 20
            _top = el.clientY - _emr_page.top
            _left = el.clientX - _emr_page.left
          }
          // 设置渲染组件定位的位置
          curDom?.setAttribute(
            'style',
            `position: absolute;
             top:${_top}px; 
             left:${_left}${_tpName == 'briefEdit' ? '' : 'px'};`
          )
        })

        // 设置当前元素的配置
        setConfig()
      })
    }
  }

  onMounted((): void => {
    let isMouseup: Ref<Boolean> = ref(false)
    let startPosX: Ref<number> = ref(0)
    let startPosY: Ref<number> = ref(0)
    let { tablMousemove, tableMousedown } = useHandleTable()

    //点击操作的节点
    let emrPage = document.querySelectorAll('.emr_page_editArea')
    for (let item of emrPage) {
      // 鼠标被按下
      item?.addEventListener('mousedown', (e: any): void => {
        let target: any = e.target
        if (
          (target && target.tagName == 'TD') ||
          target.tagName == 'TR' ||
          target.tagName == 'TBODY' ||
          target.tagName == 'TABLE'
        ) {
          // 当前操作的节点
          let _speEl = handleHtml(e) as HTMLElement
          let _curEl = (_speEl != undefined || !!_speEl ? _speEl : e.target) as HTMLElement
          configStore.$patch?.((state: IPageConfigStore) => {
            state.targetEl = e.target
            state.activeEl = _curEl
          })
          tableMousedown(e)
        } else {
          startPosX.value = e.clientX
          startPosY.value = e.clientY
        }
        isMouseup.value = false
      })
      // 鼠标被移动
      item?.addEventListener('mousemove', (e: any): void => {
        tablMousemove(e)
        if (Math.abs(e.clientX - startPosX.value) > 10 || Math.abs(e.clientY - startPosY.value) > 10) {
          isMouseup.value = true
        }
      })
      // 鼠标右击事件
      item?.addEventListener('contextmenu', (e: any): void => {
        e.preventDefault()
        // 使用自定义菜单栏目
        updatePage(e, 'contexMenu')
      })
      // // 页面双击事件
      // item?.addEventListener('dblclick', (e: any): void => {
      //   // 使用富文本编辑
      //   updatePage(e, 'briefEdit')
      // })
      // 鼠标松开事件，并且是否有选区
      item?.addEventListener('mouseup', (e: any) => {
        if (isMouseup.value) {
          let selection: any = window.getSelection && window.getSelection()
          let curRregion: any = selection.getRangeAt(0)
          let startLoc: any = curRregion.startOffset // 起始位置
          let endLoc: any = curRregion.endOffset // 终点位置
          let startNode: any = curRregion.startContainer // 起始节点
          let endNode: any = curRregion.endContainer // 终点节点
          // 判断鼠标是否选中区域
          if (startLoc !== endLoc || !startNode.isSameNode(endNode)) {
            let text: string = curRregion.toString() // 选中区域的文字
            // const el = curRregion.commonAncestorContainer   // 选中区域的Element元素
            // const contentHtml = curRregion.cloneContents()   // 选中区域的html
            // 使用富文本编辑
            if (!!text) {
              updatePage(e, 'briefEdit')
            }
          }
        } else {
          updatePage(e, getConfig(e.target.dataset.config as string) as IConfig)
        }
        isMouseup.value = false
      })
      // 页面输入事件
      item?.addEventListener('input', (e: any): void => {
        // 获取输入操作的节点
        if (!!configStore.el) {
          let filedText = document.getElementById(configStore.el)
          configStore.$patch?.((state: IPageConfigStore) => {
            if (state.val.textVal != undefined) state.val.textVal = filedText?.innerText
            // state.val.textVal = filedText?.innerText
          })
          // 设置当前元素的配置
          setConfig()
        }
      })
    }
  })
}
